package net.itzyz.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 多线程下载
 * @author dell
 *
 */
public class MulThreadDownload {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String path = "http://www.dvwh.com/15953851598.mp3";
		try {
			new MulThreadDownload().download(path, 3);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void download(String path, int threadSize) throws Exception{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		int fileLenght = conn.getContentLength();
		String fileName = getFileName(path);
		File file = new File(fileName);
		RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
		accessFile.setLength(fileLenght); //设置文件长度
		accessFile.close();
		int block = fileLenght%threadSize==0?fileLenght%threadSize:fileLenght/threadSize + 1;
		for(int thread=0; thread<threadSize; thread++){
			new DownloadThread(url,file,block,thread).start();
		}
	}
	
	public final class DownloadThread extends Thread{
		private URL url;
		private File saveFile;
		private int block;
		private int threadId;
		public DownloadThread(URL url, File saveFile, int block, int threadId){
			this.url = url;
			this.saveFile = saveFile;
			this.block = block;
			this.threadId = threadId;					
		}
		
		@Override
		public void run(){
			//计算开始位置公式：线程id*每条线程下载的数据长度= ？
		    //计算结束位置公式：（线程id +1）*每条线程下载的数据长度-1 =?
			int startPosition = threadId * block;
			int endPosition = (threadId+1) * block -1;
			try {
System.out.println("--------start---------");
				RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
				accessFile.seek(startPosition);//设置从什么位置开始写入数据
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5*1000);
				conn.setRequestProperty("Range", "bytes="+startPosition+"-"+endPosition);
				InputStream is = conn.getInputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while((len = is.read(buffer)) != -1){
					accessFile.write(buffer, 0, len);
				}
				is.close();
				accessFile.close();
System.out.println("线程"+threadId+"下载完成");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static String getFileName(String path){
		return path.substring(path.lastIndexOf("/")+1);
	}
	
	/**
	 * 取得文件的扩展名
	 * @param strFileName
	 * @return
	 */
	public static String getExtendName(String path){
		File myFile = new File(getFileName(path));
		String strFileExtend = myFile.getName();
		strFileExtend = strFileExtend.substring(strFileExtend.lastIndexOf(".")+1).toLowerCase();
		if(strFileExtend.equals("")){
			strFileExtend = "dat";
		}
		return strFileExtend;
	}
}
